#include "LogSys.h"
#include "Windows.h"
#include <sstream>
#include <iostream>

LogSys::LogSys(const std::string &fileName,bool toConsole)
{
    LogSys::toConsole=toConsole;
    fileOut.open(fileName,std::fstream::out | std::fstream::app);
}


LogSys::~LogSys(void)
{
    fileOut.close();
}


LogSys& LogSys::getInstance()
{
    // Why this works: a static variable starts existing when its codeline is executed for the 
    // first time, but does NOT stop existing at the normal end of scope. Thus, by putting the 
    // instance variable in this function, not in the class itself, it won't be made until its 
    // used. But still, we don't need to do manual clean up after it, as we would be the case 
    // with the regular "pointer to instance object as class variable" approach. Neat, eh?

    // Also, parameters should ofcourse be in a config file.
    static LogSys instance("log.txt",true);
    return instance;  
}  
const std::string LogSys::SEPARATOR=" ; ";

/**
write everything, remember timestamp 
*/
void LogSys::Write(const std::string &source,Level level,const std::string &message){

    //Using windows only time system. Should fine portable solution in the long term
    SYSTEMTIME st;
    GetSystemTime(&st);

    std::stringstream result;
    result << st.wYear << " " << st.wMonth << " " << st.wDay << " " << st.wHour << ":" << st.wMinute << ":" << st.wSecond << "." << st.wMilliseconds;
    result << SEPARATOR << source << SEPARATOR << levelNames[level] << SEPARATOR << message << std::endl;
    fileOut << result.str();
    if(toConsole)
        std::cout << result.str();
}